package org.tlipoca.smsteamachievement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.genntii.smcommon.constant.SteamApiURLConstant;
import org.genntii.smcommon.constant.SteamConstant;
import org.genntii.smcommon.result.Result;
import org.genntii.smcommon.utils.HttpClientUtil;
import org.genntii.smdomain.entity.SteamAchievement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.tlipoca.smsteamachievement.client.SteamStoreClient;
import org.tlipoca.smsteamachievement.mapper.SteamAchievementMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/steam_achievement")
public class TestController {

    @Autowired
    private SteamStoreClient steamStoreClient;

    @Autowired
    private SteamAchievementMapper steamAchievementMapper;

    @GetMapping("/achievement")
    public Result getAchievements() {
        // OpenFeign 遍历SteamStore数据库 Appid列表
        ArrayList<Integer> appidList = steamStoreClient.getSteamStoreAppidList().getData();
        ArrayList<SteamAchievement> achievements = new ArrayList<>();
        Integer lastAppid = appidList.get(appidList.size() - 1);

        for (Integer appid : appidList) {
            // 获取成就信息
            Map<String, Object> map = Map.of("key", SteamConstant.STEAM_KEY, "language", SteamConstant.STEAM_CHINESE_LANGUAGE, "appid", appid);
            JSONObject jsonObject = (JSONObject) JSON.parseObject(HttpClientUtil.doGetWithRetry(SteamApiURLConstant.GET_ACHIEVEMENT, map, 100)).get("response");
            log.info("获取成就信息成功 appid: {}", appid);

            if(jsonObject == null || jsonObject.isEmpty()) {
                log.info("appid: {} 成就信息为空", appid);
                continue;
            }

            List<SteamAchievement> achievementList = JSON.parseArray(jsonObject.get("achievements").toString(), SteamAchievement.class);

            // 抽取成就对象
            for (SteamAchievement achievement : achievementList) {
                achievement.setAppid(appid);
                achievements.add(achievement);
            }

            // 批量插入数据库
            if(achievements.size() >= 500 || appid.equals(lastAppid)) {
                log.info("开始更新Mysql...");
                steamAchievementMapper.insertAchievementBatch(achievements);
                achievements.clear();
            }

        }

        log.info("成就信息更新完成");

        return Result.success();
    }

}
